import React from 'react'
import {Row, Col, Form,Button, Table, Select, Input, Avatar, Modal, message, Checkbox, Switch,Tag,Card,DatePicker} from 'antd'
import './styles.css'
import {LeftOutlined} from '@ant-design/icons';
import Model from "./Model"
import api from "../../../api/api";
import axios from 'axios';
import { isAuthenticated } from '../../../utils/Session'
import moment from 'moment';
const FormItem = Form.Item;



const {Search} = Input;
const {Option} = Select;

@Form.create()
class Checkin extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            modelData: {
                title: "办理入住",
                visible: false,
                type: 1,//新增人员:1,添加 2,编辑
                gridList: {},
            },
            title: "办理入住",
            visible: false,
            data: [],
            identifySelectId:undefined,
            pageNum: 1,
            pageSize: 10,
            total: 0,
            selectedRowIds:[],
            setIdentify:"1",
            hiddenFlag:true,
            roomName:"",
            roomType:undefined,
            priceFrom: "",
            priceTo: "",
            belongAreaId:"",
            detailHidden:true,
            detailHiddenForMain:false,
            detailHiddenForPeople:true,
            hiddenPeopleNumber1:false,
            hiddenPeopleNumber2:true,
            hiddenPeopleNumber3:true,
            payform:true,
            areaName:"",
            dateString: [],
            modelRoom:{
                roomId:"",
                areaId:"",
                roomName:"",
                roomType:"",
                roomPrice:"",
            },
        };
    }



    componentDidMount() {
        this.getUserInfo();

      }
    columns = [
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
            className: "elementHidden",
            width: '1px'
        },
        {
            title: '区域编号',
            dataIndex: 'areaId',
            className: "elementHidden",
            key: 'areaId',
            width: '10px'
        },
        {
            title: '区域名称',
            dataIndex: 'areaName',
            key: 'areaName',
            width: '10px'
        },
        {
            title: '房间号',
            dataIndex: 'roomName',
            width: '15px',
            key: 'roomName'
        },
        {
            title: '房间类型',
            dataIndex: 'roomType',
            width: '15px',
            key: 'roomType'
        },
        {
            title: '房间价格',
            dataIndex: 'roomPrice',
            width: '15px',
            key: 'roomPrice'
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: '15px',
            key: 'status',
            render: (text, record, index) => {
                //TODO 状态值
                let state = record.status;
                let stateInfo = "";
                let color = "magenta";
                if (state == "0") {
                    stateInfo = "未入住";
                    color = "geekblue";
                }
                return (
                    <div>
                        <Tag color={color}>{stateInfo}</Tag>
                    </div>
                )
            }
        },

        {
            title: '禁用',
            dataIndex: 'isUsed',
            className: "elementHidden",
            width: '15px',
            key: 'isUsed'
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '15px',
            key: 'option',
            render: (_ext, record, Item) => {
                return (
                    <span>
                       <a className="optionMargin" onClick={() => this.onClickEdit(record)}>办理入住</a>
                    </span>
                )
            }
        }
    ];


    getCheckinList(){
        let that = this;
        axios.post(api.api_URL + "/check/selectRoomForCheckIn?pageNum=" + this.state.pageNum + "&pageSize=" + this.state.pageSize, {
            "roomName": this.state.roomName,
            "roomType":this.state.roomType,
            "priceFrom":this.state.priceFrom,
            "priceTo":this.state.priceTo,
            "belongAreaId":this.state.belongAreaId,
            "status":0,
        }, {
            headers: {
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            console.info(res)
            if (res.data.errorCode != 1) {
                return;
            }
            let totalSize = res.data.object.total;
            const dataList = [];
            for (let i = 0; i < res.data.object.records.length; i++) {
                let resContent = res.data.object.records[i];
                const content = {};
                content.key = (i + 1);
                content.id = resContent.id;
                content.areaId = resContent.areaId;
                if (resContent.areaId===1) {
                    content.areaName="天津和平区";
                }else if(resContent.areaId===2){
                    content.areaName="天津南开区";
                }
                content.roomName = resContent.roomName;
                content.roomType=resContent.roomType;
                content.roomPrice = resContent.roomPrice;
                content.status=resContent.status;
                // if (resContent.status===0) {
                //     content.status="未入住";
                // }else if(resContent.status===1){
                //     content.status="已入住";
                // }else if(resContent.status===2){
                //     content.status="已预订";
                // }
                content.isUsed =resContent.isUsed;
                dataList[i] = content;
            }
            that.setState({
                data: dataList,
                total: totalSize
            })
        }).catch(function (err) {
            console.log(err);
        });
    }


    //办理入住
    onClickEdit(item) {
        console.log(item)
        this.setState({
            detailHiddenForMain:true,
            detailHidden:false,
            areaName:item.areaName,
            modelRoom:{
                roomId:item.id,
                areaId:item.areaId,
                roomName:item.roomName,
                roomType:item.roomType,
                roomPrice:item.roomPrice,
            }


        });
    }

    //选择房间类型
    selectRoomType= (value) => {
        console.log(value)
        console.log(isAuthenticated())

        this.setState({
            roomType:value
        });
    }

    //根据用户名找用户名信息分辨出登陆用户属于哪个区，在分区查询
    getUserInfo(){
        let that =this;
        let username=isAuthenticated()
        axios.post(api.api_URL+"/employee/getUserinfoByUsername?username="+username,{},
            {
                header:{
                    "Content_Type":api.ContentType
                }
            }).then(function (res) {
            let belongAreaId=res.data.object.belongAreaId;
            that.setState({
                belongAreaId:belongAreaId
            })
            console.log(that.state.belongAreaId);
            that.getCheckinList();
        }).catch(function (err) {
            console.log(err);
        });
    }


    //分页
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getCheckinList()
        });


    }

    onclickSearch() {
        console.info("搜索");
        this.getCheckinList();
    }


    inputChange = (e) => {
            this.setState({
                roomName: e.target.value
            })
        }

    onclickReset() {
        this.setState({
            roomType:undefined,
            roomName:undefined,
            priceTo: "",
            priceFrom:"",
        },() => {
            this.getCheckinList()
        });

    };


    handleOk = e => {
        this.props.form.validateFields((error, values) => {
            console.info("values=========", values);
        })
        // console.log(e);
        // this.setState({
        //     visible: false,
        // });
    };
    handleOkForIdentify= e =>{
        let that=this;
        if (this.state.setIdentify=="2" && this.state.identityFlagPerson=="" ){
            alert("请选择审核人员身份")
        }else {
            let url = api.api_URL + "/admin/visituserinfo/setPersonIdentify";
            axios.post(url, {
                "userId":this.state.selectedRowIds,
                "identityFlag": this.state.setIdentify,
                "identityFlagPerson": this.state.identityFlagPerson,

            },{
                headers: {
                    "Authorization": localStorage.getItem('token'),
                    "Content-Type": api.ContentType
                }
            }).then(function (res) {
                that.handleCancel()
                if (res.data.code==1) {
                    message.success({content:"身份设置成功！"})
                }else{
                    message.error({content:"身份设置失败！"})
                }
                that.setState({
                    setIdentify: "1"
                })
            }).catch(function (err) {
                console.log(err);
            });
            that.setState({
                identityFlagPerson: "",
                selectedRowIds:[],
                hiddenFlag:true,
                identifySelectId:undefined,
                c1:false,
                c2:false,
            })
        }

    }
    identifyChange=(value)=>{
        let that=this;
        this.setState({
            setIdentify: value,
            identifySelectId: value,
        })
        if (value==2||value=="2"){
            that.setState({
                hiddenFlag: false
            })
        }else {
            that.setState({
                hiddenFlag: true
            })
        }
    }
    handleCancel = e => {
        this.setState({
            visible:false,
            identifySelectId:undefined,
            hiddenFlag:true,
            modelData: {
                visible: false
            },
        }, () => {
            this.refresh()
        });

    }

    priceFrom = (e) => {
        e.persist();
        console.log(e.target.value)
        this.setState({
            priceFrom: e.target.value
        })
    }

    priceTo = (e) => {
        e.persist();
        console.log(e.target.value)
        this.setState({
            priceTo: e.target.value
        })
    }

    refresh() {
        this.getCheckinList()
    }

    onRef = (ref) => {
        this.child = ref
    }
    //上一步--客人信息中的上一步
    beforeStep= e => {
        this.setState({
            detailHidden: false,
            detailHiddenForPeople:true
        })
    }
    //上一步2--支付情况中的上一步
    beforeStep2= e => {
        this.setState({
            payform:true,
            detailHiddenForPeople:false,

        })
    }

    //输入的日期
    inputdate= (value,dateString) => {
        console.log('选择的时间：', dateString)
        this.setState({
            dateString:dateString,
        })
    }
    //由选择的人数出现不同的card
    peolpeflag= (value) => {
        console.log(value.target.value)
        let e=value.target.value
        if(e==1){
            this.setState({
                hiddenPeopleNumber1: false,
                hiddenPeopleNumber2: true,
                hiddenPeopleNumber3: true,
            })
        }
        if(e==2){
            this.setState({
                hiddenPeopleNumber1: true,
                hiddenPeopleNumber2: false,
                hiddenPeopleNumber3: true,
            })
        }
        if(e==3){
            this.setState({
                hiddenPeopleNumber1: true,
                hiddenPeopleNumber2: true,
                hiddenPeopleNumber3: false
            })
        }
    }


    //返回
    returnMain = e => {
        this.setState({
            detailHiddenForMain:false,
            detailHidden: true,
            detailHiddenForPeople:true,
            payform:true,

        })

    }
    //下一步
    nextStep= e => {
        this.setState({
            detailHidden: true,
            detailHiddenForPeople:false,

        })
    }
    //下一步2
    nextStep2= e => {
        this.setState({
            payform:false,
            detailHidden: true,
            detailHiddenForPeople:true
        })
    }
    //下一步3 确定
    nextStepOk= e => {
        let that =this;
                this.props.form.validateFields((error, values) => {
                    console.info("values=========", values);
                    if(error!=null){
                      alert("请返回重新操作！")
                    }else {
                        axios.post(api.api_URL + "/check/addCheckInRecord", {
                            "room":{
                                "id":this.state.modelRoom.roomId,
                            },
                            "checkinRecord":values,
                            "dateString":this.state.dateString
                        }, {
                            headers: {
                                "Content-Type": api.ContentType
                            }
                        }).then(function (res) {
                            console.log(res)
                            console.log(res.data.errorCode)
                            if (res.data.errorCode != 1) {
                                return;
                            }
                            if (res.data.errorCode==1) {
                                message.success({content:"办理成功！"})
                                that.setState({
                                    detailHiddenForMain:false,
                                    payform:true,
                                    detailHidden: true,
                                    detailHiddenForPeople:true,
                                });

                            }else{
                                alert("请检查数据");
                                message.error({content:"办理失败！"})
                            }

                            that.refresh();
                        })
                    }
                })
    }

    render() {
        const { getFieldDecorator, getFieldError} = this.props.form
        const { RangePicker } = DatePicker;
        const {selectedRowKeys } = this.state;
        const CheckboxGroup = Checkbox.Group;
        const CheckBox=Checkbox;
        let { c1, c2} = this.state
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys) => {
                this.setState({
                    selectedRowIds : selectedRowKeys.map(Number),
                    selectedRowKeys
                })
                console.log(`selectedRowKeys: ${selectedRowKeys}`);
                console.log(this.state.selectedRowIds)
            },
        };
        return (
            <div className="girdBg">
                <div className={this.state.detailHiddenForMain === true ? "elementHidden" : "elementShow"}>
                    <Row className="searchBox">
                        <Col span={24}>
                            <Select showSearch={true} optionFilterProp="children" placeholder="请选择房间类型" style={{width: 250, marginLeft: 30}}
                                    onChange={this.selectRoomType}  allowClear  value={this.state.roomType}>
                                <option key="单人间">单人间</option>
                                <option key="双人间">双人间</option>
                            </Select>
                            <Search style={{width: 250,marginLeft:30}}
                                    placeholder="请输入房间号" onChange={this.inputChange}  allowClear value={this.state.roomName}
                            />
                        </Col>
                    </Row>
                    <Row className="searchBox">
                        <Col span={18}>
                            <input style={{width: 100,marginLeft:30}}
                                   placeholder="请输入价格" onChange={this.priceFrom}  value={this.state.priceFrom} allowClear
                            />
                            <span  style={{width: 10,marginLeft:15}}>  ---   </span>
                            <input style={{width: 100,marginLeft:15}}
                                   placeholder="请输入价格" onChange={this.priceTo} value={this.state.priceTo} allowClear
                            />
                            <Button icon={"search"} type='primary' style={{marginLeft: 30}}
                                    onClick={this.onclickSearch.bind(this)}>搜索</Button>
                            <Button icon={"reset"} style={{marginLeft: 30}} onClick={this.onclickReset.bind(this)}>重置</Button>
                        </Col>
                    </Row>
                    <Row style={{margin: 30}}>
                        <Table
                            columns={this.columns}
                            dataSource={this.state.data}
                            scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                            rowSelection={rowSelection}
                            rowKey={record =>record.userId}
                            columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                                const fun = () => ({style: {whiteSpace: 'nowrap'}});
                                item.onHeaderCell = fun;
                                item.onCell = fun;
                                return item;
                            })}
                            pagination={{
                                simple: false,
                                current: this.state.pageNum,
                                total: this.state.total,
                                pageSize: this.state.pageSize,
                                showTotal: (count = this.state.total) => {
                                    return '共' + count + '条'
                                },
                                onChange: (current, pageSize) => {
                                    this.onBaseClick(current, pageSize)
                                }
                            }}
                        />
                    </Row>
                    <Model data={this.state.modelData} handleCancel={this.handleCancel} refresh={this.refresh}
                           onRef={this.onRef} history={this.props.history}/>
                </div>




                {/*房间信息的model*/}
                <div className={this.state.detailHidden === true ? "elementHidden" : "elementShow"} style={{marginLeft:10,marginRight:10}}>
                    <Row>
                        <Col span={24}>
                            <div className="returnBtn" style={{marginLeft:10,marginTop:10}} onClick={this.returnMain.bind(this)}>
                                <LeftOutlined/>
                            </div>
                            <Card title="房间信息" bordered={false}>
                                <Form name="control-ref"
                                      labelCol={{ span: 4 }}
                                      wrapperCol={{ span: 16 }}
                                      layout="horizontal"
                                      style={{marginLeft:290}}
                                >
                                    <FormItem  label="区域" name="areaName" >
                                        <Input style={{width:200}}  value={this.state.areaName} />
                                    </FormItem>
                                    <FormItem  label="房间号" name="roomName" >
                                        <Input style={{width:200}} value={this.state.modelRoom.roomName}  />
                                    </FormItem>
                                    <FormItem  label="类型" name="roomType" >
                                        <Input style={{width:200}} value={this.state.modelRoom.roomType}  />
                                    </FormItem>
                                    <FormItem  label="价格" name="roomPrice" >
                                        <Input style={{width:200}} value={this.state.modelRoom.roomPrice} />
                                    </FormItem>
                                    <FormItem  label="请输入天数" name="rentTerm" >
                                        <Input.Group compact style={{width:310}} >
                                            {getFieldDecorator("rentTerm", {
                                            })(
                                                <Input style={{ width: '17%' }}  />
                                            )}

                                                <RangePicker format="YYYY-MM-DD HH:mm:ss"
                                                             showTime={{ defaultValue: [moment('12:00:00', 'HH:mm:ss'), moment('12:00:00','HH:mm:ss')],}}
                                                             style={{ width: '83%' }}
                                                             onChange={this.inputdate}  />

                                        </Input.Group>
                                    </FormItem>
                                </Form>
                                <Button type="primary" style={{marginLeft:500}} onClick={this.nextStep.bind(this)}>下一步</Button>
                            </Card>
                        </Col>
                    </Row>
                </div>
                {/*客人信息的model*/}
                <div className={this.state.detailHiddenForPeople === true ? "elementHidden" : "elementShow"} style={{marginLeft:10,marginRight:10}}>
                    <Row>
                        <Col span={24}>
                            <div className="returnBtn" style={{marginLeft:10,marginTop:10}} onClick={this.returnMain.bind(this)}>
                                <LeftOutlined/>
                            </div>
                            <Card title="房客信息" bordered={false}>
                                <Form name="control-ref"
                                      labelCol={{ span: 4 }}
                                      wrapperCol={{ span: 16 }}
                                      layout="horizontal"
                                      style={{marginLeft:170}}
                                      onOk={this.nextStep2}

                                >
                                    <FormItem  label="请选择入住人数" >
                                        <select onChange={this.peolpeflag}>
                                            <option key={1}>1</option>
                                            <option key={2}>2</option>
                                            <option key={3}>3</option>
                                        </select>
                                    </FormItem>
                                     <div hidden={this.state.hiddenPeopleNumber1} style={{marginLeft:90}}>
                                         <FormItem  label="姓名" name="name1" >
                                             {getFieldDecorator("name1", {
                                             })(
                                                 <Input style={{width:200}}/>
                                             )}
                                         </FormItem>
                                         <FormItem  label="性别" name="gender1" >
                                             {getFieldDecorator("gender1", {
                                             })(
                                                 <Input style={{width:200}} />
                                             )}

                                         </FormItem>
                                         <FormItem  label="身份证" name="idcard1" >
                                             {getFieldDecorator("idcard1", {
                                             })(
                                                 <Input style={{width:200}} />
                                             )}
                                         </FormItem>
                                         <FormItem  label="电话" name="phone1" >
                                             {getFieldDecorator("phone1", {
                                             })(
                                                 <Input style={{width:200}} />
                                             )}
                                         </FormItem>
                                     </div>
                                     <div hidden={this.state.hiddenPeopleNumber2}>
                                         <Row>
                                             <Col span={12}>
                                                 <FormItem  label="姓名" name="name1" >
                                                     {getFieldDecorator("name1", {
                                                     })(
                                                         <Input style={{width:200}}  />
                                                     )}
                                                 </FormItem>
                                                 <FormItem  label="性别" name="gender1" >
                                                     {getFieldDecorator("gender1", {
                                                     })(
                                                         <Input style={{width:200}} />
                                                     )}
                                                 </FormItem>
                                                 <FormItem  label="身份证" name="idcard1" >
                                                     {getFieldDecorator("idcard1", {
                                                     })(
                                                         <Input style={{width:200}}  />
                                                     )}
                                                 </FormItem>
                                                 <FormItem  label="电话" name="phone1" >
                                                     {getFieldDecorator("phone1", {
                                                     })(
                                                         <Input style={{width:200}} />
                                                     )}
                                                 </FormItem>
                                             </Col>
                                             <Col span={12}>
                                                 <FormItem  label="姓名" name="name2" >
                                                     {getFieldDecorator("name2", {
                                                     })(
                                                         <Input style={{width:200}}  />
                                                     )}
                                                 </FormItem>
                                                 <FormItem  label="性别" name="gender2" >
                                                     {getFieldDecorator("gender2", {
                                                     })(
                                                         <Input style={{width:200}}    />
                                                     )}
                                                 </FormItem>
                                                 <FormItem  label="身份证" name="idcard2" >
                                                     {getFieldDecorator("idcard2", {
                                                     })(
                                                         <Input style={{width:200}}  />
                                                     )}
                                                 </FormItem>
                                                 <FormItem  label="电话" name="phone2" >
                                                     {getFieldDecorator("phone2", {
                                                     })(
                                                         <Input style={{width:200}} />
                                                     )}
                                                 </FormItem>
                                             </Col>
                                         </Row>
                                     </div>
                                    <div hidden={this.state.hiddenPeopleNumber3}>
                                        <Row>
                                            <Col span={8}>
                                                <FormItem  label="姓名" name="name1" >
                                                    {getFieldDecorator("name1", {
                                                    })(
                                                        <Input style={{width:200}}  />
                                                    )}
                                                </FormItem>
                                                <FormItem  label="性别" name="gender1" >
                                                    {getFieldDecorator("gender1", {
                                                    })(
                                                        <Input style={{width:200}}  />
                                                    )}
                                                </FormItem>
                                                <FormItem  label="身份证" name="idcard1" >
                                                    {getFieldDecorator("idcard1", {
                                                    })(
                                                        <Input style={{width:200}} />
                                                    )}
                                                </FormItem>
                                                <FormItem  label="电话" name="phone1" >
                                                    {getFieldDecorator("phone1", {
                                                    })(
                                                        <Input style={{width:200}} />
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={8}>
                                                <FormItem  label="姓名" name="name2" >
                                                    {getFieldDecorator("name2", {
                                                    })(
                                                        <Input style={{width:200}}   />
                                                    )}
                                                </FormItem>
                                                <FormItem  label="性别" name="gender2" >
                                                    {getFieldDecorator("gender2", {
                                                    })(
                                                        <Input style={{width:200}}   />
                                                    )}
                                                </FormItem>
                                                <FormItem  label="身份证" name="idcard2" >
                                                    {getFieldDecorator("idcard2", {
                                                    })(
                                                        <Input style={{width:200}}  />
                                                    )}
                                                </FormItem>
                                                <FormItem  label="电话" name="phone2" >
                                                    {getFieldDecorator("phone2", {
                                                    })(
                                                        <Input style={{width:200}}   />
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={8}>
                                                <FormItem  label="姓名" name="name3" >
                                                    {getFieldDecorator("name3", {
                                                    })(
                                                        <Input style={{width:200}}  />
                                                    )}
                                                </FormItem>
                                                <FormItem  label="性别" name="gender3" >
                                                    {getFieldDecorator("gender3", {
                                                    })(
                                                        <Input style={{width:200}}   />
                                                    )}
                                                </FormItem>
                                                <FormItem  label="身份证" name="idcard3" >
                                                    {getFieldDecorator("idcard3", {
                                                    })(
                                                        <Input style={{width:200}}  />
                                                    )}
                                                </FormItem>
                                                <FormItem  label="电话" name="phone3" >
                                                    {getFieldDecorator("phone3", {
                                                    })(
                                                        <Input style={{width:200}}  />
                                                    )}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </div>
                                </Form>
                                <Button type="primary" style={{marginLeft:400,marginRight:50}} onClick={this.beforeStep.bind(this)}>上一步</Button>
                                <Button type="primary" type="submit" onClick={this.nextStep2.bind(this)}>下一步</Button>
                            </Card>
                        </Col>
                    </Row>
                </div>

                {/*支付情况*/}
                <div className={this.state.payform === true ? "elementHidden" : "elementShow"} style={{marginLeft:10,marginRight:10}}>
                    <Row>
                        <Col span={24}>
                            <div className="returnBtn" style={{marginLeft:10,marginTop:10}} onClick={this.returnMain.bind(this)}>
                                <LeftOutlined/>
                            </div>
                            <Card title="支付情况" bordered={false}>
                                <Form name="control-ref"
                                      labelCol={{ span: 4 }}
                                      wrapperCol={{ span: 16 }}
                                      layout="horizontal"
                                      style={{marginLeft:290}}

                                >
                                    <FormItem  label="支付金额" name="money" >
                                        {getFieldDecorator("money", {
                                            rules: [{ required: true, message: '请填写支付金额!',whitespace: true,}] ,
                                        })(
                                            <Input style={{width:200}}   />
                                        )}
                                    </FormItem>
                                    <FormItem  label="支付方式" name="payType" >
                                        {getFieldDecorator("payType", {
                                            rules: [{ required: true, message: '请填写支付方式!',whitespace: true,}] ,
                                        })(
                                            <Input style={{width:200}}  />
                                        )}
                                    </FormItem>
                                </Form>
                                <Button type="primary" style={{marginLeft:400,marginRight:50}} onClick={this.beforeStep2.bind(this)}>上一步</Button>
                                <Button type="primary" onClick={this.nextStepOk.bind(this)}>确定</Button>
                            </Card>
                        </Col>
                    </Row>
                </div>
            </div>
        )
    }
}

export default Checkin
